package com.typhoon.dubbo_provider.util;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import com.alibaba.druid.pool.DruidDataSourceFactory;

/**
 * 简化数据源配置类
 * 
 * @author Typhoon
 * @date 2017-08-22 11:27 Tuesday
 * @since V1.3.1
 */
public class DataSourceUtils {

    public static Properties p       = null;
    public static String     confile = "jdbc.properties";

    static {
        p = new Properties();
        InputStream inputStream = null;
        try {
            inputStream = DataSourceUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            inputStream = new BufferedInputStream(inputStream);
            p.load(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static DataSource getDataSource() {
        try {
            return DruidDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static JdbcTemplate getJdbcTemplate() {
        DataSource   dataSource   = getDataSource();
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        return jdbcTemplate;
    }
    
    public static NamedParameterJdbcTemplate getNamedJdbcTemplate() {
    	 DataSource   dataSource   = getDataSource();
    	 NamedParameterJdbcTemplate namedJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
    	 return namedJdbcTemplate;
    }
}
